<html>
<head>

<title>Groovy Goodness: A Bit of metaClass DSL</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: A Bit of metaClass DSL</h3>

<div class="post">
<p>When we add behaviour to classes with the <code>metaClass</code> property we can use a simple DSL. We pass a closure to the <code>metaClass</code> method where we group the definitions for the new behaviour. If we add multiple methods with the same name we must use &lt;&lt;, otherwise we can just set a closure to the method name. To add a static method we use 'static' and define the methods.</p>
<pre class="brush:groovy">
String.metaClass {
    or &lt;&lt; { String s -&gt; delegate.plus(' or ').plus(s) }
    or &lt;&lt; { List l -&gt; delegate.findAll(&quot;(${l.join('|')})&quot;) }
    and { String s -&gt; delegate.plus(' and ').plus(s) }
    'static' {
        groovy { 'Yeah man!' }
    }
}

assert 'Groovy or Java?' == (&quot;Groovy&quot; | &quot;Java?&quot;)
assert ['o', 'o', 'y'] == (&quot;Groovy&quot; | ['o', 'y'])
assert 'Groovy and Java!' == (&quot;Groovy&quot; &amp; &quot;Java!&quot;)

assert 'Yeah man!' == String.groovy()
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>